package com.example.hybridmobiledemo.module.main.model.shop.classification;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.hybridmobiledemo.R;
import com.example.hybridmobiledemo.bean.SHSQLInfo;
import com.example.hybridmobiledemo.databinding.ActivityShopBinding;
import com.example.hybridmobiledemo.module.main.bean.NewsInfo;
import com.example.hybridmobiledemo.module.main.bean.SCNewsAllInfo;
import com.example.hybridmobiledemo.module.main.fragment.news.EcoFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.EntertainmentFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.LawFragment;
import com.example.hybridmobiledemo.module.main.fragment.news.SociologyFragment;
import com.example.hybridmobiledemo.module.main.model.news.search.SearchActivity;
import com.example.hybridmobiledemo.module.main.model.shop.bean.CommodityInfo;
import com.example.hybridmobiledemo.module.main.model.shop.bean.CommodityTypeIdInfo;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.BathroomFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.ClearPaperFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.PurificationFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.ThermalFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.TissueFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.fragment.TraTonicFragment;
import com.example.hybridmobiledemo.module.main.model.shop.classification.search.ShopSearchActivity;
import com.example.hybridmobiledemo.module.main.model.shop.classification.shopcart.ShopCartActivity;
import com.example.hybridmobiledemo.util.MyDataAdapter;
import com.example.hybridmobiledemo.util.OkHttpUtils;
import com.example.hybridmobiledemo.view.MyPagerAdapter;
import com.example.hybridmobiledemo.view.NewsRvAdapter;
import com.example.hybridmobiledemo.view.ViewPageAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class ShopActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener {
    private ActivityShopBinding binding;
    private ViewPager shopVp;
    private LinearLayout shopLLPoint;
    private ArrayList<String> imgUrls = new ArrayList<>();
    private ArrayList<ImageView> imageViews; //存放图片的集合
    private int lastPosition;
    private boolean isRunning = false; //viewpager是否在自动轮询
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    private EditText editText;
    List<Fragment> fragmentList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        binding = ActivityShopBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/Commodity/getAll")
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                CommodityInfo info = gson.fromJson(json, CommodityInfo.class);
                                List<CommodityInfo.DataBean> list = info.getData();
                                for (int i = 0; i < list.size(); i++) {
                                    String pic = list.get(i).getPic();
                                    imgUrls.add(pic);
                                }
                                initView();
                                initData();
                                initAdapter();
                                new Thread(() -> {
                                    isRunning = true;
                                    while (isRunning) {
                                        try {
                                            Thread.sleep(3000);
                                        } catch (InterruptedException e) {
                                            e.printStackTrace();
                                        }
                                        if (isRunning) {
                                            runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                    shopVp.setCurrentItem(shopVp.getCurrentItem() + 1);
                                                }
                                            });
                                        }
                                    }
                                }).start();
                            }

                            @Override
                            public void onFailure(Exception e) {

                            }
                        });
            }
        }).start();
        initTitle();
    }
    private void initAdapter() {
        shopLLPoint.getChildAt(0).setBackgroundResource(R.drawable.radiobutton_on_background);
        lastPosition = 0;
        MyPagerAdapter adapter = new MyPagerAdapter();
        adapter.setImageViews(imageViews);
        shopVp.setAdapter(adapter);
        shopVp.setCurrentItem(5000000);
    }
    private void initData() {
        imageViews = new ArrayList<>();
        ImageView imageView;
        View pointView;
        for (int i = 0; i < 5; i++) {
            imageView = new ImageView(ShopActivity.this);
            int rollImg = (int) (Math.random() * imgUrls.size());
            try {
                Glide.with(ShopActivity.this).load(imgUrls.get(rollImg)).into(imageView);
            } catch (Exception e) {
                Glide.with(ShopActivity.this).load(R.drawable.ic_launcher_background).into(imageView);
            }
            imageViews.add(imageView);
            pointView = new View(ShopActivity.this);
            pointView.setBackgroundResource(R.drawable.radiobutton_off_background);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(25, 25);
            if (i != 0) {
                layoutParams.leftMargin = 10;
            }
            shopLLPoint.addView(pointView, layoutParams);
        }
    }

    private void initView() {
        shopVp = binding.shopVp;
        shopLLPoint = binding.shopLLPoint;
        shopVp.setOnPageChangeListener(this);
        tabLayout = binding.shopTabLayout;
        viewPager2 = binding.shopViewPager2;
        editText = binding.editShopSearch;
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEARCH) {
                    String search = editText.getText().toString().trim();
                    if (search.equals("")) {
                        Toast.makeText(ShopActivity.this, "请输入搜索内容", Toast.LENGTH_SHORT).show();
                    } else  {
                        Intent intent = new Intent(ShopActivity.this, ShopSearchActivity.class);
                        intent.putExtra("search", search);
                        startActivity(intent);
                    }

                    return true;
                }
                return false;
            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                OkHttpUtils.builder()
                        .url("interface/CommodityType/getAll")
                        .addParam("userId", "ODky")
                        .get()
                        .async(new OkHttpUtils.AsyncCallBack() {
                            @Override
                            public void onResponse(String json) {
                                Gson gson = new Gson();
                                CommodityTypeIdInfo typeId = gson.fromJson(json, CommodityTypeIdInfo.class);
                                List<CommodityTypeIdInfo.DataBean> list = typeId.getData();
                                for (int i = 0; i < list.size(); i++) {
                                    String id = String.valueOf(list.get(i).getId());
                                    String commodityTypeName = list.get(i).getCommodityTypeName();
                                    switch (commodityTypeName) {
                                        case "纸巾":
                                            fragmentList.add(TissueFragment.newInstance("纸巾",
                                                    "", id));
                                            break;
                                        case "清洁纸品":
                                            fragmentList.add(ClearPaperFragment.newInstance("清洁纸品",
                                                    "", id));
                                            break;
                                        case "传统滋补":
                                            fragmentList.add(TraTonicFragment.newInstance("传统滋补",
                                                    "", id));
                                            break;
                                        case "净化除味":
                                            fragmentList.add(PurificationFragment.newInstance("净化除味",
                                                    "", id));
                                            break;
                                        case "浴室用品":
                                            fragmentList.add(BathroomFragment.newInstance("浴室用品",
                                                    "", id));
                                            break;
                                        case "保暖防护":
                                            fragmentList.add(ThermalFragment.newInstance("保暖防护",
                                                    "", id));
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                ViewPageAdapter adapter = new ViewPageAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
                                viewPager2.setAdapter(adapter);
                                new TabLayoutMediator(tabLayout, viewPager2, true, new TabLayoutMediator.TabConfigurationStrategy() {
                                    @Override
                                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                                        tab.setText(fragmentList.get(position).getArguments().getString("title"));
                                    }
                                }).attach();
                            }

                            @Override
                            public void onFailure(Exception e) {
                            }
                        });
            }
        }).start();
    }

    private void initTitle() {
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.shop_bar);
        TextView tvShopBack = findViewById(R.id.tvShopBack);
        ImageView imgShopBack = findViewById(R.id.imgShopBack);
        ImageView imgShopMore = findViewById(R.id.imgShopMore);
        tvShopBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        imgShopBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        imgShopMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog dialog =new AlertDialog.Builder(ShopActivity.this).create();
                dialog.show();
                Window window = dialog.getWindow();
                window.setGravity(Gravity.TOP);
                window.setContentView(R.layout.item_cla_more);
                TextView tvDiaShopCart = window.findViewById(R.id.tvDiaShopCart);
                TextView tvDiaCusList = window.findViewById(R.id.tvDiaCusList);
                TextView tvDiaShopList = window.findViewById(R.id.tvDiaShopList);
                tvDiaShopCart.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        startActivity(new Intent(ShopActivity.this, ShopCartActivity.class));
                    }
                });
                tvDiaCusList.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
                tvDiaShopList.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        binding = null;
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int newPosition = position % 5;
        shopLLPoint.getChildAt(lastPosition).setBackgroundResource(R.drawable.radiobutton_off_background);
        shopLLPoint.getChildAt(newPosition).setBackgroundResource(R.drawable.radiobutton_on_background);
        lastPosition = newPosition;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}